package midp;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;

public abstract class Dialog {
	protected Display display;
	protected DialogListener listener;
	protected Displayable restore;
	private int eventID;

	private boolean inited = false;

	protected Dialog(Display display) {
		this.display = display;
	}

	public int getEventID() {
		return eventID;
	}

	public void setEventID(int eventID) {
		this.eventID = eventID;
	}

	public void doAction(int code) {
		Displayable curr = display.getCurrent();
		if (curr != getDisplayable())
			return;

		if (restore != null) {
			display.setCurrent(restore);
		} else {
			display.setCurrent(new Form(""));
		}

		if (listener != null) {
			listener.dialogAction(this, code);
		}
	}

	/**
	 * 初始化代码
	 */
	protected void init() {

	}

	public final void display() {
		Displayable curr = display.getCurrent();
		if (!inited) {
			synchronized (this) {
				init();
				inited = true;
			}
		}
		Displayable dialog = getDisplayable();

		if (curr != dialog) {
			restore = curr;
			display.setCurrent(dialog);
		}
	}

	public void display(int event) {
		Displayable curr = display.getCurrent();
		Displayable dialog = getDisplayable();
		this.eventID = event;

		if (curr != dialog) {
			restore = curr;
			display.setCurrent(dialog);
		}
	}

	public DialogListener getDialogListener() {
		return listener;
	}

	protected abstract Displayable getDisplayable();

	public void setDialogListener(DialogListener l) {
		listener = l;
	}

}
